extends CharacterBody2D

@onready var animations = $Animations

@export var interactSequence:Array

var npcConfig 
var currentSequenceIndex = 0
var dialogShowBottomCenterPos
var currentCommand


#type just say 1
var sentences = []


func _physics_process(delta):
	processZIndex()
	

func init(pos, face, spriteFrameResource, _npcConfig):
	position = pos
	var spriteFrames = ResourcePreload.resources[spriteFrameResource]
	animations.sprite_frames = spriteFrames
	animations.play("Idle" + face)
	
	npcConfig = _npcConfig
	if npcConfig.type == "1":
		initByTypeSay()
		

func initByTypeSay():
	var sentencesConfig = ConfigClasses.SentencesConfig.groupConfigArrDict[str(int(npcConfig.param1))]
	interactSequence = []
	
	for sentenceConfig in sentencesConfig:
		var sequence = "say(\"%s\")" % [sentenceConfig.sentence]
		interactSequence.append(sequence)
	
	
func processZIndex():
	z_index = position.y
	

func interact():
	if currentSequenceIndex >= interactSequence.size():
		currentSequenceIndex = 0
	
	var sequenceCommandStr = interactSequence[currentSequenceIndex]
	currentSequenceIndex += 1
	
	var result = Global.parseSequenceCommand(sequenceCommandStr)
	currentCommand = result
	
	if result["methodName"] == "say":
		var content = result["params"][0]
		dialogShowBottomCenterPos =  position - Vector2(0, Global.cellSize * 1.6)
		NpcDialog.startShow(content, dialogShowBottomCenterPos)
	

func onExitInteractableArea():
	currentSequenceIndex = 0
	if currentCommand != null and currentCommand["methodName"] == "say":
		NpcDialog.hide()
		currentCommand = null
	
